package com.project.user.controller.controller;

import com.project.user.entity.UserPhoneCodeExample;
import com.project.user.entity.entitly.UserInformationView;
import com.project.user.entity.entitly.UserPhoneCode;
import com.project.user.mapper.UserPhoneCodeMapper;
import com.untils.MybatisClass;
import com.untils.StaticMessage;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserCodeController implements com.project.user.controller.UserCodeController {

    @Override
    public int setUserPhoneCode(String phone) throws Exception {

        int userCodeString = StaticMessage.DEFAULT_EXAMPLE;
        UserPhoneCode userCode = new UserPhoneCode(phone);

        // 后端处理相关
        SqlSession sqlSession = MybatisClass.getSqlSession();
        UserPhoneCodeMapper userCodeMapper = sqlSession.getMapper(UserPhoneCodeMapper.class);
        try {
            int sauces = userCodeMapper.insert(userCode);
            sqlSession.commit();
            userCodeString = sauces;
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.close();
        } finally {
            sqlSession.close();
        }
        return userCodeString;
    }

    @Override
    public Map<String, Object> getUserPhoneCode(String phone, String phoneCode) throws Exception {

        UserPhoneCode userPhoneCode = new UserPhoneCode();
        UserInfoController userInfoController = new UserInfoController();
        UserInformationView userInfo = new UserInformationView();
        Map<String, Object> map = new HashMap<>();
        boolean isSuccessfully = false;

        try {
            userPhoneCode = this.userPhoneCode(phone, phoneCode);
            userInfo=userInfoController.UserInfo(-1, userPhoneCode.getPhoneNumber(),null);
            isSuccessfully = userPhoneCode.getPhoneStarttime().getTime() > System.currentTimeMillis();
        } catch (Exception ignored) {
            // Not Found UserCode
        }
        
        map.put("is-successfully", isSuccessfully);
        map.put("is-object", userInfo);
        return map;

    }

    @Override
    public UserPhoneCode userPhoneCode(String phone, String phoneCode) throws Exception {

        UserPhoneCode UserPhoneCode = new UserPhoneCode();
        SqlSession sqlSession = MybatisClass.getSqlSession();
        UserPhoneCodeMapper userCodeMapper = sqlSession.getMapper(UserPhoneCodeMapper.class);
        UserPhoneCodeExample userCodeExample = new UserPhoneCodeExample();

        try {
            userCodeExample.createCriteria().andIdIsNotNull().andPhoneNumberEqualTo(phone).andPhoneCodeEqualTo(phoneCode);
            List<UserPhoneCode> userCodes = userCodeMapper.selectByExample(userCodeExample);
            UserPhoneCode = userCodes.get(userCodes.size() - 1);
        } finally {
            sqlSession.close();
        }

        return UserPhoneCode;
    }
}
